<?php

namespace app\admin\service;

use app\admin\model\UM as UM;
use app\common\model\Member;
use app\index\service\MemberTokenService;
use ShidianUtil\Utils\CheckUtil;
use think\exception\ValidateException;
use think\facade\Log;

/**
 * Class MemberExchangePhoneService
 * @package app\admin\service
 */
class MemberExchangePhoneService
{
    /**
     * 新增
     * @param UM $user
     * @param array $params
     * @return  void
     */
    public function add(UM $user, array $params): void
    {
        // 交换两个账号的登录手机号
        $a = $params['a'] ?? '';
        $b = $params['b'] ?? '';

        if (is_blank($a)) {
            throw new ValidateException('请输入A号码');
        }
        if (!CheckUtil::isPhoneNumber($a)) {
            throw new ValidateException('请输入正确的A号码');
        }
        if (is_blank($b)) {
            throw new ValidateException('请输入B号码');
        }
        if (!CheckUtil::isPhoneNumber($b)) {
            throw new ValidateException('请输入正确的B号码');
        }

        $aMember = Member::where('phone', $a)->find();

        $bMember = Member::where('phone', $b)->find();

        if (is_null($aMember)) {
            throw new ValidateException('A不存在');
        }

        if (is_null($bMember)) {
            throw new ValidateException('B不存在');
        }

        $aMember->phone = $b;
        $aMember->save();

        $bMember->phone = $a;
        $bMember->save();

        // 退出登录
        $this->getMemberTokenService()->delete($aMember->id);
        $this->getMemberTokenService()->delete($bMember->id);


        Log::info('号码对换A:' . $a . ' B:' . $b);

    }

    private function getMemberTokenService(): MemberTokenService
    {
        return app(MemberTokenService::class);
    }
}
